import { getInfo, getUserDetailInfo, login } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth.js'
const state = {
  token: getToken(), // 用户token
  userInfo: {}// 用户基本信息
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(context, data) {
    // 发请求
    try {
      const token = await login(data)
      // 保存token
      context.commit('setToken', token)
      // 保存时间戳
      setTimeStamp()
    } catch (e) {
      console.error(e)
      return Promise.reject(e)
    }
  },
  async getUserInfo(context) {
    const userInfo = await getInfo()
    const userDetailInfo = await getUserDetailInfo(userInfo.userId)
    context.commit('setUserInfo', { ...userInfo, ...userDetailInfo })
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
